import configparser
import argparse
from consul import Consul


class ConsulConfig:
    def __init__(self, host: str, port: int, token: str, dc: str):
        self.host = host
        self.port = port
        self.token = token
        self.dc = dc

    def __str__(self):
        return f"""
            host: {self.host}
            port: {self.port}
            token: {self.token}
            dc: {self.dc}
        """


class Config:
    def __init__(self, path: str):
        self._conf = configparser.ConfigParser()
        self._conf.read(path)

    def _get_config(self, section: str):
        sec = self._conf.items(section)
        cnf = {s[0]: s[1] for s in sec}
        return ConsulConfig(**cnf)

    def get_src_config(self):
        return self._get_config("src")

    def get_dst_config(self):
        return self._get_config("dst")


class Connect:
    def __init__(self, conf: ConsulConfig):
        self._conn = Consul(
            host=conf.host,
            port=int(conf.port),
            token=conf.token,
            dc=conf.dc
        )

    def get(self, item: str):
        _, keys = self._conn.kv.get(item, recurse=True)
        return {d['Key']: d['Value'].decode('utf-8') for d in keys if d['Value'] is not None}

    def put(self, key: str, value: str):
        return self._conn.kv.put(key, value)


def get_args():
    args_parse = argparse.ArgumentParser(description="微服务配置同步脚本")
    args_parse.add_argument(
        "--item", type=str, required=False, help="需要同步配置的微服务", default=""
    )
    return args_parse.parse_args()


if __name__ == '__main__':
    args = get_args()
    config = Config("config.ini")
    src_conf, dst_conf = config.get_src_config(), config.get_dst_config()
    src_consul, dst_consul = Connect(src_conf), Connect(dst_conf)
    copy_conf = src_consul.get(args.item)
    for data in copy_conf:
        dst_consul.put(data, copy_conf.get(data))
        print(f"""CREAT {data} in {dst_conf.host}""")
